<template>
  <div id="centerDiv" class="mapcontainer">
    <!--    <div class="spinner-container" id="my-spinner">-->
    <!--      <ProgressBar-->
    <!--        :currentProgress='currentProgress'-->
    <!--        lineBackgroundColor='#ccc'-->
    <!--        lineForeground='#369CCB'-->
    <!--        style="width: 1200px;height: 10px"-->
    <!--      ></ProgressBar>-->
    <!--    </div>-->
    <div class="mask"></div>
    <mars-map :url="configUrl" :widgetUrl="widgetUrl" @onload="onMapload"/>
  </div>
</template>

<script>
import MarsMap from '@/components/mars-work/mars-map.vue'
import axios from "axios";
import flvjs from 'flv.js'
import Spinner from 'vue-simple-spinner'
import ProgressBar from 'vue2-steps-progress'
import {eventBus} from '@/main.js'
// import {s_startLiveStream,s_closeLiveStream,s_getAllInfo} from "@/api/dmag/big_screen";
export let car_graphicLayer
export let camera_graphicLayer
export let building_graphicLayer
let cameraHistory
let cameraPointsMap = {}
let global_map
const camerasData = [
  {
    name: "camera_1",
    position: [106.929419, 39.480432, 1250],
    camera_info: "rtsp://admin:gn123456@192.168.9.182:554",
    info_1: "监控信息",
    info_2: "位置：卡口"
  }
]
const buildingsData = [
  {
    name: "库房",
    position: [106.927048, 39.475747, 1255.7],
    height: 20,
    positions: [[106.92672, 39.476264, 1255.6], [106.926308, 39.475739, 1256.1], [106.927239, 39.475291, 1255.3], [106.927665, 39.475828, 1256.1]]
  },
  {
    name: "生活区",
    position: [106.927283, 39.477868, 1269],
    height: 20,
    positions: [[106.928346, 39.477675, 1273.1], [106.926506, 39.477183, 1268.2], [106.926172, 39.478101, 1268.9], [106.927915, 39.47857, 1268.4]]
  },
  {
    name: "煤棚",
    position: [106.934258, 39.469291, 1272.2],
    height: 30,
    positions: [[106.934124, 39.467998, 1251.8], [106.934899, 39.46809, 1252.5], [106.934424, 39.470574, 1249.9], [106.933608, 39.470477, 1249.6]]
  },
  {
    name: "停车场",
    position: [106.931069, 39.476544, 1252.9],
    height: 20,
    positions: [[106.930318, 39.477202, 1253.5], [106.931318, 39.477362, 1252.5], [106.931546, 39.476086, 1253.4], [106.930797, 39.475936, 1249.3]]
  },
  {
    name: "办公区",
    position: [106.927606, 39.476789, 1255.8],
    height: 20,
    positions: [[106.92827, 39.477215, 1255.2], [106.926667, 39.4769, 1255.9], [106.927394, 39.4765, 1255.7], [106.928268, 39.476688, 1255.7]]
  }
]
const buildingsData2 = [
  // {
  //   name: "库房",
  //   position: [106.927048, 39.475747, 1255.7],
  //   height: 20,
  //   positions: [[106.92672, 39.476264, 1255.6], [106.926308, 39.475739, 1256.1], [106.927239, 39.475291, 1255.3], [106.927665, 39.475828, 1256.1]]
  // },
  // [106.93083, 39.496953, 1322.2], [106.930829, 39.497216, 1317.1], [106.931408, 39.497222, 1324.7], [106.931297, 39.496948, 1317.8]
  {
    name: "生活区",
    position: [106.931047, 39.497049, 1317.6],
    height: 20,
    positions: [[106.93083, 39.496953, 1322.2], [106.930829, 39.497216, 1317.1], [106.931408, 39.497222, 1324.7], [106.931297, 39.496948, 1317.8]]
  },
  {
    name: "生产区",
    position: [106.928572, 39.497777, 1317.5]
  },
  {
    name: "办公区",
    position: [106.928103, 39.496447, 1314.4],
    height: 20,
    positions: [[106.928041, 39.496191, 1318], [106.92785, 39.496679, 1317.5], [106.928455, 39.496794, 1314.2], [106.928483, 39.496672, 1314.3], [106.927993, 39.49657, 1314.6], [106.928101, 39.496251, 1314.5], [106.928267, 39.496289, 1314.3], [106.928309, 39.496241, 1316.1], [106.92805, 39.49619, 1317.9]]
  },
  {
    name: "停车场",
    position: [106.928408, 39.495558, 1316.1],
    height: 20,
    positions: [[106.928263, 39.495178, 1315], [106.928011, 39.495886, 1314.9], [106.928953, 39.495955, 1317.5], [106.928965, 39.495183, 1314.5]]
  }
]
let carsData = []

let cycletimes = 0

let myTiles3dLayer

/**
 * 移除图层
 *
 * @returns {void}
 */
function removeLayer() {
  if (myTiles3dLayer) {
    map.basemap = 2022 // 切换到默认影像底图

    map.removeLayer(myTiles3dLayer, true)
    myTiles3dLayer = null
  }
}

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "index",

  components: {
    MarsMap,
    ProgressBar
  },

  data() {
    const basePathUrl = window.basePathUrl || ''
    return {
      currentProgress: 0,
      targetProgress: 100,
      animationDuration: 15000, // 动画持续时间（毫秒）
      animationInterval: null, // 动画计时器
      show: true,
      flvPlayer: null,
      configUrl: basePathUrl + 'config/config.json',
      widgetUrl: basePathUrl + 'config/widget.json',

    }
  },
  computed: {},
  mounted() {
    this.animationInterval = setInterval(() => {
      const increment = (this.targetProgress - this.currentProgress) / (this.animationDuration / 1000);
      this.currentProgress += increment;

      if (this.currentProgress >= this.targetProgress) {
        this.currentProgress = this.targetProgress;
        clearInterval(this.animationInterval);
      }
    }, 1000);
    setTimeout(function () {
      var spinner = document.getElementById('my-spinner');
      spinner.style.display = 'none';
    }, 12000); // 30 seconds
  },
  methods: {
    play() {
      this.flvPlayer.play();
    },
    // 地图构造完成回调

    onMapload(map) {
      map.on('centerXY', function (event) {
        console.log('在widget进行了坐标定位', event)
      })
      car_graphicLayer = new mars3d.layer.GraphicLayer()
      building_graphicLayer = new mars3d.layer.GraphicLayer()
      camera_graphicLayer = new mars3d.layer.GraphicLayer()
      map.addLayer(building_graphicLayer)
      map.addLayer(camera_graphicLayer)
      // 暂停刷新车辆&摄像头
      // getCarsData()

      // initMap_caiQu1(map)
      initMap_part1(map)
      global_map = map

      // 在map地图上绑定右键菜单
      // const defaultContextmenuItems = map.getDefaultContextMenu() // 内置的默认右键菜单获取方法
      // map.bindContextMenu(defaultContextmenuItems) // 可以删减defaultContextmenuItems数组内值


      const control = map.getControl("homeButton", "type")
      control.on(mars3d.EventType.click, function (event) {
        console.log("center3 您单击了home按钮", event)
        let currentCenter = map.getCameraView()
        if (currentCenter != null) {
          console.log("center3", currentCenter)
        }
      })

    }
  }

}

function addOrUpdateCameraPoint(vehicleNo, longitude, latitude, height) {
  if (cameraPointsMap.hasOwnProperty(vehicleNo)) {
    // 如果键已存在，进行更新
    cameraPointsMap[vehicleNo] = [longitude, latitude, height];
  } else {
    // 如果键不存在，进行添加
    cameraPointsMap[vehicleNo] = [longitude, latitude, height];
  }
}

function getCameraPoint(vehicleNo) {
  if (cameraPointsMap.hasOwnProperty(vehicleNo)) {
    // 如果键存在，返回对应的值
    return cameraPointsMap[vehicleNo];
  } else {
    // 如果键不存在，返回空数组或者其他适当的默认值
    return [];
  }
}

function deleteCameraPoint(vehicleNo) {
  if (cameraPointsMap.hasOwnProperty(vehicleNo)) {
    // 如果键存在，使用 delete 运算符删除键对
    delete cameraPointsMap[vehicleNo];
  }
}

function getCarsData() {
  try {
    s_getAllInfo().then(response => {
      carsData = response
    });
  } catch (error) {
    console.error(error);
  }
  setTimeout(() => {
    getCarsData()
    // 方法区
  }, 5000);
}

// 三维模型：caiqu1
function initMap_caiQu1(map) {
  // removeLayer()
  myTiles3dLayer = new mars3d.layer.TilesetLayer({
    // url: 'http://222.74.94.190:338/map/tileset.json',
    url: 'http://127.0.0.1:8081/cai_3dtiles4/tileset.json',
    maximumScreenSpaceError: 16,
    cullRequestsWhileMoving: false,
    cacheBytes: 2073741824,
    rotation: {z: 360},
    position: {alt: 38.8},
    progressiveResolutionHeightFraction: 0.2,
    maximumCacheOverflowBytes: 4147483648,
    maximumMemoryUsage: 4048,
    cullRequestsWhileMovingMultiplier: 10,
    dynamicScreenSpaceError: true,
    foveatedScreenSpaceError: false,
    preloadWhenHidden: true,
    preferLeaves: true,
    shadows: false,
    skipLevelOfDetail: true,


    // 真实----"lat":39.755464,"lng":106.885124
    // center: {lat: 39.785464, lng: 106.865124, alt: 4000.0, heading: 156.1, pitch: -38.6},
    // center: {lat: 39.775464, lng: 106.871124, alt: 3000.0, heading: 156.1, pitch: -38.6},

    // {
    //   "lat": 39.773457,
    //   "lng": 106.874337,
    //   "alt": 2997.4,
    //   "heading": 156.1,
    //   "pitch": -38.6
    // }
    center: {lat: 39.773457, lng: 106.874337, alt: 2997.4, heading: 156.1, pitch: -38.6},
    loadSiblings: true,

    luminanceAtZenith: 0.1,

    enableDebugWireframe: true, // 是否可以进行三角网的切换显示
    flyTo: true
  })

  map.addLayer(myTiles3dLayer)

  const graphic = new mars3d.graphic.WallEntity({
    positions: [[106.92939, 39.480492, 1250.3], [106.931308, 39.481471, 1251.9], [106.933009, 39.482016, 1253.3], [106.93712, 39.481709, 1256.4], [106.940828, 39.48192, 1244.5], [106.942972, 39.482379, 1248.4], [106.945208, 39.482854, 1262.2], [106.950531, 39.483237, 1288.3], [106.952157, 39.481898, 1294.1], [106.952242, 39.4799, 1291.9], [106.954222, 39.475842, 1288.8], [106.958099, 39.470644, 1291.5], [106.95918, 39.468914, 1292.4], [106.959046, 39.466198, 1286.8], [106.958259, 39.465394, 1285.9], [106.958731, 39.463388, 1289.3], [106.959323, 39.461261, 1294.1], [106.958908, 39.460111, 1293.6], [106.961658, 39.457303, 1301.7], [106.962941, 39.453296, 1301.5], [106.965143, 39.449826, 1302.3], [106.965437, 39.448905, 1297.4], [106.964407, 39.448313, 1293], [106.964044, 39.447553, 1291.3], [106.958329, 39.447801, 1238.1], [106.934778, 39.452495, 1264.3], [106.926157, 39.461927, 1258.4], [106.924082, 39.477908, 1241.1]],
    style: {
      closure: true,
      diffHeight: 50,
      // 动画线材质
      materialType: mars3d.MaterialType.LineFlow,
      materialOptions: {
        image: "http://222.74.94.190:338/res/img/textures/fence.png",
        color: "rgba(32,144,255,0.71)",
        color2: "rgba(124,196,236,0.71)",
        speed: 5,
        axisY: true
      }
    },
    attr: {remark: "示例1"}
  })
  map.graphicLayer.addGraphic(graphic)
  for (let i = 0; i < buildingsData.length; i++) {
    const item = buildingsData[i]

    const divGraphic = new mars3d.graphic.DivGraphic({
      position: item.position,
      style: {
        html: `
        <div class="mars-spot-board">
        <h5>${item.name}</h5>
        </div>
        <div class="mars-spot-line"></div>`,
        offsetY: -60,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM
      },
      attr: {name: item.name}
    })
    building_graphicLayer.addGraphic(divGraphic)
    const graphic = new mars3d.graphic.PolygonEntity({
      positions: item.positions,
      style: {
        // height: 50,
        diffHeight: item.height,
        materialType: mars3d.MaterialType.PolyGradient,
        materialOptions: {
          color: "#3388cc",
          alphaPower: 0.7
        },
        highlight: {
          materialOptions: {
            color: "rgba(0,128,255,0.38)",
            alphaPower: 1.5
          }
        }
      }
    })
    map.graphicLayer.addGraphic(graphic)
  }

  cameraHistory = new mars3d.thing.CameraHistory({
    limit: {
      // 限定视角范围 矿场2 模型中心位置:106.885848,39.755462,0        "lat": 39.785464, "lng": 106.865124,
      position: Cesium.Cartesian3.fromDegrees(106.874337, 39.773457, 2997.4),
      radius: 15000.0,
      debugExtent: false
    },
    maxCacheCount: 999
  })
  map.addThing(cameraHistory)


  let currentCenter = map.getCameraView()
  if (currentCenter != null) {
    console.log("current center2", currentCenter)
  }


  map.graphicLayer.on(mars3d.EventType.rightClick, function (event) {
    const graphic = event.graphic
    console.log("clicked")
    if (graphic) {
      map.flyToPoint(graphic.position, {
        radius: Cesium.Cartesian3.distance(graphic.position, map.camera.positionWC) * 0.1
      })
      graphic.setCameraOptions({
        radius: Cesium.Cartesian3.distance(graphic.position, map.camera.positionWC)
      })
    }
  })
  car_graphicLayer.on(mars3d.EventType.rightClick, function (event) {
    const graphic = event.graphic
    console.log("clicked")
    if (graphic) {
      map.flyToPoint(graphic.position, {
        radius: Cesium.Cartesian3.distance(graphic.position, map.camera.positionWC) * 0.1
      })
      graphic.setCameraOptions({
        radius: Cesium.Cartesian3.distance(graphic.position, map.camera.positionWC)
      })
    }
  })

  setTimeout(() => {
    map.setSceneOptions({
      // caiqu1
      // center: {"lat": 39.773457, "lng": 106.874337, "alt": 2997.4, "heading": 156.1, "pitch": -38.6},
      // part1 {"lat":39.505504,"lng":106.944314,"alt":2453.3,"heading":240,"pitch":-38.6}
      center: {"lat": 39.773457, "lng": 106.874337, "alt": 2997.4, "heading": 156.1, "pitch": -38.6}
    })
    // 暂停刷新车辆&摄像头
    // initCamera()
    // refreshCars(map)
    // 方法区
  }, 12000);
}

// 三维模型：part1
function initMap_part1(map) {
  // removeLayer()
  myTiles3dLayer = new mars3d.layer.TilesetLayer({
    // url: 'http://222.74.94.190:338/map/tileset.json',
    url: 'http://127.0.0.1:8081/cai_3dtiles_part1/tileset.json',
    maximumScreenSpaceError: 16,
    cullRequestsWhileMoving: false,
    cacheBytes: 2073741824,
    rotation: {z: 360},
    position: {alt: 38.8},
    progressiveResolutionHeightFraction: 0.2,
    maximumCacheOverflowBytes: 4147483648,
    maximumMemoryUsage: 4048,
    cullRequestsWhileMovingMultiplier: 10,
    dynamicScreenSpaceError: true,
    foveatedScreenSpaceError: false,
    preloadWhenHidden: true,
    preferLeaves: true,
    shadows: false,
    skipLevelOfDetail: true,


    // 真实----"lat":39.755464,"lng":106.885124
    // center: {lat: 39.785464, lng: 106.865124, alt: 4000.0, heading: 156.1, pitch: -38.6},
    // center: {lat: 39.775464, lng: 106.871124, alt: 3000.0, heading: 156.1, pitch: -38.6},

    // {
    //   "lat": 39.773457,
    //   "lng": 106.874337,
    //   "alt": 2997.4,
    //   "heading": 156.1,
    //   "pitch": -38.6
    // },

    center: {lat: 39.505504, lng: 106.944314, alt: 2453.3, heading: 240, pitch: -38.6},
    loadSiblings: true,

    luminanceAtZenith: 0.1,

    enableDebugWireframe: true, // 是否可以进行三角网的切换显示
    flyTo: true
  })

  map.addLayer(myTiles3dLayer)

  // // 围墙1
  // const graphic = new mars3d.graphic.WallEntity({
  //   positions: [[106.92939, 39.480492, 1250.3], [106.931308, 39.481471, 1251.9], [106.933009, 39.482016, 1253.3], [106.93712, 39.481709, 1256.4], [106.940828, 39.48192, 1244.5], [106.942972, 39.482379, 1248.4], [106.945208, 39.482854, 1262.2], [106.950531, 39.483237, 1288.3], [106.952157, 39.481898, 1294.1], [106.952242, 39.4799, 1291.9], [106.954222, 39.475842, 1288.8], [106.958099, 39.470644, 1291.5], [106.95918, 39.468914, 1292.4], [106.959046, 39.466198, 1286.8], [106.958259, 39.465394, 1285.9], [106.958731, 39.463388, 1289.3], [106.959323, 39.461261, 1294.1], [106.958908, 39.460111, 1293.6], [106.961658, 39.457303, 1301.7], [106.962941, 39.453296, 1301.5], [106.965143, 39.449826, 1302.3], [106.965437, 39.448905, 1297.4], [106.964407, 39.448313, 1293], [106.964044, 39.447553, 1291.3], [106.958329, 39.447801, 1238.1], [106.934778, 39.452495, 1264.3], [106.926157, 39.461927, 1258.4], [106.924082, 39.477908, 1241.1]],
  //   style: {
  //     closure: true,
  //     diffHeight: 50,
  //     // 动画线材质
  //     materialType: mars3d.MaterialType.LineFlow,
  //     materialOptions: {
  //       image: "http://222.74.94.190:338/res/img/textures/fence.png",
  //       color: "rgba(32,144,255,0.71)",
  //       color2: "rgba(124,196,236,0.71)",
  //       speed: 5,
  //       axisY: true
  //     }
  //   },
  //   attr: {remark: "示例1"}
  // })
  // map.graphicLayer.addGraphic(graphic)

  // 围墙2
  const wall2 = new mars3d.graphic.WallEntity({
    positions: [[106.93313, 39.498731, 1322.1], [106.933115, 39.498319, 1322.7], [106.933213, 39.497461, 1322.1], [106.9327, 39.497414, 1322.1], [106.93272, 39.496886, 1322.1], [106.931403, 39.49524, 1322.1], [106.93047, 39.495117, 1322.1], [106.928243, 39.494968, 1313.9], [106.927795, 39.496005, 1322.1], [106.926679, 39.498561, 1322.1], [106.929498, 39.499187, 1322.1], [106.931536, 39.49883, 1323.6], [106.932163, 39.498871, 1323.3], [106.931884, 39.498734, 1322.1], [106.93216, 39.498731, 1323.7], [106.932397, 39.498704, 1325.8], [106.932409, 39.4988, 1320.5], [106.932607, 39.498873, 1321.3], [106.933151, 39.498686, 1322.2], [106.933143, 39.498687, 1324.8]],
    style: {
      closure: true,
      diffHeight: 50,
      // 动画线材质
      materialType: mars3d.MaterialType.LineFlow,
      materialOptions: {
        // image: '../../../public/img/res/fence.png',
        image: "http://222.74.94.190:338/res/img/textures/fence.png",
        color: "rgba(32,144,255,0.71)",
        color2: "rgba(124,196,236,0.71)",
        speed: 5,
        axisY: true
      }
    },
    attr: {remark: "wall-2"}
  })
  map.graphicLayer.addGraphic(wall2)

  for (let i = 0; i < buildingsData2.length; i++) {
    const item = buildingsData2[i]

    const divGraphic = new mars3d.graphic.DivGraphic({
      position: item.position,
      style: {
        html: `
        <div class="mars-spot-board">
        <h5>${item.name}</h5>
        </div>
        <div class="mars-spot-line"></div>`,
        offsetY: -60,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM
      },
      attr: {name: item.name}
    })
    building_graphicLayer.addGraphic(divGraphic)
    const graphic = new mars3d.graphic.PolygonEntity({
      positions: item.positions,
      style: {
        // height: 50,
        diffHeight: item.height,
        materialType: mars3d.MaterialType.PolyGradient,
        materialOptions: {
          color: "#3388cc",
          alphaPower: 0.7
        },
        highlight: {
          materialOptions: {
            color: "rgba(0,128,255,0.38)",
            alphaPower: 1.5
          }
        }
      }
    })
    map.graphicLayer.addGraphic(graphic)
  }

  cameraHistory = new mars3d.thing.CameraHistory({
    limit: {
      // 限定视角范围 矿场2 模型中心位置:106.885848,39.755462,0
      // {"lat":39.505504,"lng":106.944314,"alt":2453.3,"heading":240,"pitch":-38.6}
      position: Cesium.Cartesian3.fromDegrees(106.944314, 39.505504, 2453.3),
      radius: 15000.0,
      debugExtent: false
    },
    maxCacheCount: 999
  })
  map.addThing(cameraHistory)

  map.graphicLayer.on(mars3d.EventType.rightClick, function (event) {
    const graphic = event.graphic
    console.log("clicked")
    if (graphic) {
      map.flyToPoint(graphic.position, {
        radius: Cesium.Cartesian3.distance(graphic.position, map.camera.positionWC) * 0.1
      })
      graphic.setCameraOptions({
        radius: Cesium.Cartesian3.distance(graphic.position, map.camera.positionWC)
      })
    }
  })
  car_graphicLayer.on(mars3d.EventType.rightClick, function (event) {
    const graphic = event.graphic
    console.log("clicked")
    if (graphic) {
      map.flyToPoint(graphic.position, {
        radius: Cesium.Cartesian3.distance(graphic.position, map.camera.positionWC) * 0.1
      })
      graphic.setCameraOptions({
        radius: Cesium.Cartesian3.distance(graphic.position, map.camera.positionWC)
      })
    }
  })


  setTimeout(() => {
    map.setSceneOptions({
      // caiqu1
      // center: {"lat": 39.773457, "lng": 106.874337, "alt": 2997.4, "heading": 156.1, "pitch": -38.6},
      // part1 {"lat":39.505504,"lng":106.944314,"alt":2453.3,"heading":240,"pitch":-38.6}
      center: {
        "lat": 39.505504, "lng": 106.944314, "alt": 2453.3, "heading": 240, "pitch": -38.6
      }
    })
    // 暂停刷新车辆&摄像头
    // initCamera()
    // refreshCars(map)
    // 方法区
  }, 12000);

}

function initCamera() {
  for (let i = 0; i < camerasData.length; i++) {
    const item = camerasData[i]
    const camera = new mars3d.graphic.Route(
      {
        name: item.name,
        speed: 10,
        clockLoop: true,
        positions: [
          item.position
        ],
        model: {
          show: true,
          url: "http://222.74.94.190:338/res/models/camera.gltf",
          scale: 3,
          minimumPixelSize: 0
        },
        billboard: {
          image: "http://222.74.94.190:338/res/myimg/camera.png",
          scale: 1,
          pixelOffsetY: -50,
          minimumPixelSize: 10
        },
        polyline: {
          color: "#ffff00",
          width: 1,
          clampToGround: true,
          classificationType: Cesium.ClassificationType.CESIUM_3D_TILE
        },
        attr: {
          info_1: "监控卡口",
          info_2: item.info_1,
          camera_info: item.camera_info
        }
      }
    )
    bindPopup(camera)
    camera_graphicLayer.addGraphic(camera)
  }
}

function refreshCars(map) {
  car_graphicLayer = new mars3d.layer.GraphicLayer()
  map.addLayer(car_graphicLayer)
  console.log(carsData)
  for (let i = 0; i < carsData.length; i++) {
    const item = carsData[i]
    const car = new mars3d.graphic.Route(
      {
        clockLoop: true,
        model: {
          show: true,
          url: "http://222.74.94.190:338/res/models/car.gltf",
          scale: 3,
          minimumPixelSize: 0
        },
        billboard: {
          image: "http://222.74.94.190:338/res/myimg/car.png",
          scale: 1,
          pixelOffsetY: -50,
          description: item.vehicleNo,
          minimumPixelSize: 6
        },
        label: {
          description: item.vehicleNo
        },
        // polyline: {
        //   color: "#ffff00",
        //   width: 1,
        //   clampToGround: true,
        //   classificationType: Cesium.ClassificationType.CESIUM_3D_TILE
        // },
        attr: {
          info_1: item.vehicleType,
          info_2: item.vehicleNo,
          info_3: item.speed,
          camera_info: item.streamAddr,
          sim: item.sim,
          exist: true,
        },
        clampToTileset: true, // 贴模型，但效率不高，车多就卡
        frameRateHeight: 240,
        minHeight: 1000,
        maxHeight: 1400
      }
    )
    bindPopup(car)
    car_graphicLayer.addGraphic(car)
  }
  changePosition(map)
}

function changePosition(map) {
  cycletimes++
  if (cycletimes < 30) {
    car_graphicLayer.eachGraphic((graphic) => {
      if (graphic === undefined) {
        return
      }
      graphic.attr.exist = false;
      for (let i = 0; i < carsData.length; i++) {
        const item = carsData[i]
        if (item.vehicleNo === graphic.attr.info_2) {
          graphic.attr.exist = true
          let jingdu
          let weidu
          let gaodu
          let jingdu1
          let weidu1
          let gaodu1
          [jingdu, weidu, gaodu] = getCameraPoint(item.vehicleNo);
          addOrUpdateCameraPoint(item.vehicleNo, item.lon, item.lat, item.altitude);
          [jingdu1, weidu1, gaodu1] = getCameraPoint(item.vehicleNo);
          // console.log("变经度维度高度：",jingdu1-jingdu,",",weidu1-weidu,",",gaodu1-gaodu)
          if (Math.abs(jingdu1 - jingdu) > 0.004 || Math.abs(weidu1 - weidu) > 0.004) {
            car_graphicLayer.removeGraphic(graphic);
            deleteCameraPoint(graphic.attr.info_2)
          } else {
            // console.log("差距",graphic.position.longitude-item.lon,graphic.position.latitude-item.lat,graphic.position.altitude-item.altitude)
            graphic.addDynamicPosition([item.lon, item.lat, item.altitude], 20)
          }
        }
        // 按time秒运动至指定位置
      }

    })
    car_graphicLayer.eachGraphic((graphic) => {
      if (graphic === undefined) {
        return
      }
      if (graphic.attr.exist === false) {
        car_graphicLayer.removeGraphic(graphic)
        deleteCameraPoint(graphic.attr.info_2)
      }

    })
    setTimeout(() => {
      changePosition(map)
      // 方法区
    }, 20000);
  } else {
    cycletimes = 0
    console.log("刷新了车辆")
    map.removeLayer(car_graphicLayer)
    refreshCars(map)
  }
}

function bindPopup(entity) {
  entity.bindPopup(
    `<div
      <div style="font-size: 34px;">类别：<span id="info_1" > </span></div>
      <a href="http://222.74.94.190:327/mangroves/maintenance/vehicleMileage/" id="info_2" target="_blank" style="font-size: 34px;"></a>
      <div><span id="info_3" style="font-size: 34px;"> </span></div>
      <div><span id="info_4" style="font-size: 34px;"> </span></div>
      <div id="videoBox_1" style="position: relative; width: 100%; height: 100%; left: 0;right: 0;display:none">
        <video id="videoElement_1" controls autoplay muted style="display: inline-block; left : 0; width: 684px; height: 567px; float: left;"> </video>
        <video id="videoElement_2" controls autoplay muted style="display: inline-block; right : 0; width: 684px; height: 567px; float: left;"> </video>
        </div>
      <div id="videoBox_2" style="position: relative; width: 100%; height: 100%; left: 0;right: 0;display:none">
          <video id="videoElement_3" controls autoplay muted style="display: inline-block; left : 0; width: 684px; height: 567px; float: left;"> </video>
        </div>
      </div>`,
    {closeOnClick: true}
  )
  entity.on(mars3d.EventType.click, function (event) {

  })
  entity.on(mars3d.EventType.popupOpen, function (event) {
    if (entity.attr.info_1 !== "监控卡口") {
      eventBus.$emit('openCar', entity.attr.info_2)
      const container = event.container // popup对应的DOM
      const params = entity.property
      const clientId = entity.attr.sim; // 替换为实际的clientId值
      const hrefbox = document.getElementById('info_2')
      hrefbox.href += clientId
      console.log(entity)
      console.log(entity.attr.sim)
      const videobox = document.getElementById('videoBox_1');
      videobox.style.display = "block"
      let flvPlayer
      // 发送GET请求
      s_startLiveStream(clientId, 1)
        .then((response) => {
          const data = response.data;
          if (data.msg === '离线的客户端') {
            console.error('检测到离线的客户端，程序退出');
            return
          }
          // console.log("Cccccccccccc",data)
          if (flvjs.isSupported()) {
            const videoElement = document.getElementById('videoElement_1');
            flvPlayer = flvjs.createPlayer({
              type: 'flv',
              isLive: true,
              hasAudio: false,
              url: data
            });
            flvPlayer.attachMediaElement(videoElement);
            flvPlayer.load();
            flvPlayer.play();
          }
        })
        // 方法区
        .catch(function (error) {
          // 请求出错的处理
          console.error("请求出错:", error);
        })
      s_startLiveStream(clientId, 2)
        .then((response) => {
          const data = response.data;
          if (data.msg === '离线的客户端') {
            console.error('检测到离线的客户端，程序退出');
            return
          }
          if (flvjs.isSupported()) {
            const videoElement = document.getElementById('videoElement_2');
            const flvPlayer = flvjs.createPlayer({
              type: 'flv',
              isLive: true,
              hasAudio: false,
              url: data
            });
            flvPlayer.attachMediaElement(videoElement);
            flvPlayer.load();
            flvPlayer.play();
          }
        })
        // 方法区
        .catch(function (error) {
          // 请求出错的处理
          console.error("请求出错:", error);
        });
      console.log("打开了弹窗")
    } else if (entity.attr.info_1 === "监控卡口") {
      const videobox = document.getElementById('videoBox_2');
      videobox.style.display = "block"
      axios.get("http://192.168.6.135:8099/start_stream", {
        params: {
          rtsp_url: entity.attr.camera_info
        }
      })
        .then((response) => {
          const data = response.data;
          console.log(data)
          if (data.msg === '离线的客户端') {
            console.error('检测到离线的客户端，程序退出');
            return
          }
          if (flvjs.isSupported()) {
            const flvstream = data.flv_url.replace('localhost', "192.168.6.135");
            console.log(flvstream)
            const videoElement = document.getElementById('videoElement_3');
            const flvPlayer = flvjs.createPlayer({
              type: 'flv',
              isLive: true,
              hasAudio: false,
              url: flvstream
            });
            console.log(1)
            flvPlayer.attachMediaElement(videoElement);
            flvPlayer.load();
            flvPlayer.play();
          }
        })
        // 方法区
        .catch(function (error) {
          // 请求出错的处理
          console.error("请求出错:", error);
        });
    }
  })

  entity.on(mars3d.EventType.popupClose, function (event) {
      const container = event.container // popup对应的DOM
      const params = entity.property
      const clientId = entity.attr.sim; // 替换为实际的clientId值
      let videobox_1 = document.getElementById('videoBox_1');
      videobox_1.style.display = "none"
      let videobox_2 = document.getElementById('videoBox_2');
      videobox_2.style.display = "none"
      if (entity.attr.info_1 !== "监控卡口") {
        eventBus.$emit('closeCar', entity.attr.info_2)
        // 发送get请求
        s_closeLiveStream(clientId, 1)
          .then(function (response) {
            const data = response.data;
            if (data.msg === '离线的客户端') {
              console.log('检测到离线的客户端，程序退出');
              return
            }
            console.log(data);
          })
          .catch(function (error) {
            // 请求出错的处理
            console.error("请求出错:", error);
          });
        s_closeLiveStream(clientId, 2)
          .then(function (response) {
            const data = response.data;
            if (data.msg === '离线的客户端') {
              console.log('检测到离线的客户端，程序退出');
              return
            }
            console.log(data);
          })
          .catch(function (error) {
            // 请求出错的处理
            console.error("请求出错:", error);
          });
        console.log("关闭了弹窗")
      } else {
        // axios.get("http://192.168.6.135:8099/stop_stream", {
        //   params: {
        //     stream_id: entity.attr.camera_info
        //   }
        // })
        //   .then(function(response) {
        //     const data = response.data;
        //     if (data.msg === '离线的客户端') {
        //       console.log('检测到离线的客户端，程序退出');
        //       return
        //     }
        //     console.log(data);
        //   })
        //   .catch(function(error) {
        //     // 请求出错的处理
        //     console.error("请求出错:", error);
        //   });
      }
    }
  )
  // // 刷新局部DOM,不影响popup面板的其他控件操作
  entity.on(mars3d.EventType.postRender, function (event) {
    const container = event.container // popup对应的DOM
    const params = entity.property
    if (!params) {
      return
    }
    const info_1 = container.querySelector("#info_1")
    if (info_1) {
      if (entity.attr.info_1 === "1") {
        info_1.innerHTML = "自卸车"
      } else if (entity.attr.info_1 === "0") {
        info_1.innerHTML = "挖掘机"
      } else {
        info_1.innerHTML = "监控卡口"
      }
    }
    const info_2 = container.querySelector("#info_2")
    if (info_2) {
      if (entity.attr.info_1 === "1" || entity.attr.info_1 === "0") {
        info_2.innerHTML = ("车牌号：" + entity.attr.info_2) || ""
      } else
        info_2.innerHTML = entity.attr.info_2 || ""
    }
    const info_3 = container.querySelector("#info_3")
    if (info_3) {
      if (entity.attr.info_3) {
        info_3.innerHTML = ("车速：" + entity.attr.info_3 / 100 + " m/s") || ""
      } else
        info_3.innerHTML = entity.attr.info_3 || ""
    }
    const info_4 = container.querySelector("#info_4")
    if (info_4) {
      info_4.innerHTML = entity.attr.info_4 || ""
    }
  })
}
</script>

<style>
@import '../../../public/temp/css/divGraphic.css';

.mapcontainer {
  position: relative;
  height: 100%;
  overflow: hidden;
}

.mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('../../../public/myimg/back2.png');
  background-size: cover;
  z-index: 1;
  pointer-events: none;
  opacity: 0.9; /* 设置透明度为 0.5 */
}

.spinner-container {
  display: flex;
  justify-content: center;
  align-items: center;
  left: 400px;
  right: 400px;
  height: 100%;
}

</style>
